﻿using Lanbt.Core.Cache;
using Lanbt.Core.Entity.Dto;
using Lanbt.Core.Entity.Dto.lanbt_system_config;
using Lanbt.Core.Entity.EntityDB;
using Lanbt.Core.Entity.Enums;
using Lanbt.Core.Repository.SqlService.IRepository;
using Lanbt.Core.Service.SqlService.IService;
using Lanbt.Core.Utility.ExceptionExtent;
using Lanbt.Core.Utility.Extent;

namespace Lanbt.Core.Service.SqlService
{
    public class ConfigService : ServiceBase, IConfigService
    {
        private readonly ISystemConfigRepository _systemConfigRepository;
        private readonly IUserConfigRepository _userConfigRepository;

        public ConfigService(ISystemConfigRepository systemConfigRepository, IUserConfigRepository userConfigRepository)
        {
            _systemConfigRepository = systemConfigRepository;
            _userConfigRepository = userConfigRepository;
        }

        public async Task<ResultOutput> GetSystemConfig(SystemConfigKey key)
        {
            if (key.Description() == key.ToString())
            {
                throw new LanbtException(ExceptionModel.PARAMS_ERROR, "系统配置键不存在");
            }
            var value = CacheFactory.Cache.GetCache<string>(key.Description());
            if(value.IsNullOrEmpty())
            {
                var config = await _systemConfigRepository.FirstOrDefault(q => q.Key == key.Description());
                value = config?.Value;
                CacheFactory.Cache.SetCache(key.Description(), value, DateTime.Now.AddHours(1));
            }
            return new ResultOutput
            {
                Result = value
            };
        }

        public async Task<ResultOutput> GetUserConfig(UserConfigKey key)
        {
            if (key.Description() == key.ToString())
            {
                throw new LanbtException(ExceptionModel.PARAMS_ERROR, "用户配置键不存在");
            }
            var value = CacheFactory.Cache.GetCache<string>(key.Description() + "_" + CurrentUser.Id.ToString());
            if (value.IsNullOrEmpty())
            {
                var config = await _userConfigRepository.FirstOrDefault(q =>q.UserId == CurrentUser.Id && q.Key == key.Description());
                value = config?.Value;
                CacheFactory.Cache.SetCache(key.Description() + "_" + CurrentUser.Id.ToString(), value, DateTime.Now.AddHours(1));
            }
            return new ResultOutput
            {
                Result = value
            };
        }

        public async Task<ResultOutput> OperationConfig(ConfigInputDto input)
        {
            if(input.SystemKey != SystemConfigKey.None)
            {
                if (input.SystemKey.Description() == input.SystemKey.ToString())
                {
                    throw new LanbtException(ExceptionModel.PARAMS_ERROR, "系统配置键不存在");
                }
                var config = await _systemConfigRepository.FirstOrDefault(q => q.Key == input.SystemKey.Description());
                if (config == null)
                {
                    config = new lanbt_system_config
                    {
                        Key = input.SystemKey.Description(),
                        Value = input.value,
                    };
                    await _systemConfigRepository.InsertOne(config);
                }
                else
                {
                    config.Value = input.value;
                    await _systemConfigRepository.UpdateOne(config);
                    CacheFactory.Cache.RemoveCache(input.SystemKey.Description());
                }
                CacheFactory.Cache.SetCache<string>(input.SystemKey.Description(), input.value, DateTime.Now.AddHours(1));
            }
            else
            {
                if (input.UserKey.Description() == input.UserKey.ToString())
                {
                    throw new LanbtException(ExceptionModel.PARAMS_ERROR, "用户配置键不存在");
                }
                var config = await _userConfigRepository.FirstOrDefault(q => q.UserId == CurrentUser.Id && q.Key == input.UserKey.Description());
                if (config == null)
                {
                    config = new lanbt_user_config
                    {
                        UserId = CurrentUser.Id,
                        Key = input.UserKey.Description(),
                        Value = input.value,
                    };
                    await _userConfigRepository.InsertOne(config);
                }
                else
                {
                    config.Value = input.value;
                    await _userConfigRepository.UpdateOne(config);
                    CacheFactory.Cache.RemoveCache(input.UserKey.Description() + "_" + CurrentUser.Id.ToString());
                }
                CacheFactory.Cache.SetCache<string>(input.UserKey.Description() + "_" + CurrentUser.Id.ToString(), input.value, DateTime.Now.AddHours(1));
            }
            return new ResultOutput();
        }

        public async Task<ResultOutput> DeleteSystemConfig(SystemConfigKey key)
        {
            if (key.Description() == key.ToString())
            {
                throw new LanbtException(ExceptionModel.PARAMS_ERROR, "系统配置键不存在");
            }
            var config = await _systemConfigRepository.FirstOrDefault(q => q.Key == key.Description());
            if (config.IsNull())
            {
                throw new LanbtException(ExceptionModel.ENTITY_EXISTEN, "系统配置");
            }
            await _systemConfigRepository.Delete_false(config);
            CacheFactory.Cache.RemoveCache(key.Description());
            return new ResultOutput();
        }

        public async Task<ResultOutput> DeleteUserConfig(UserConfigKey key)
        {
            if (key.Description() == key.ToString())
            {
                throw new LanbtException(ExceptionModel.PARAMS_ERROR, "用户配置键不存在");
            }
            var config = await _userConfigRepository.FirstOrDefault(q => q.UserId == CurrentUser.Id && q.Key == key.Description());
            if (config.IsNull())
            {
                throw new LanbtException(ExceptionModel.ENTITY_EXISTEN, "系统配置");
            }
            await _userConfigRepository.Delete_false(config);
            CacheFactory.Cache.RemoveCache(key.Description()+"_"+CurrentUser.Id.ToString());
            return new ResultOutput();
        }
    }
}
